package com.ms3ds.mineInfo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ms3ds.common.core.domain.R;
import com.ms3ds.deviceData.api.RemoteDeviceService;
import com.ms3ds.deviceData.api.domain.Device;
import com.ms3ds.mineInfo.api.RemoteAreaService;
import com.ms3ds.mineInfo.api.domain.Area;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ms3ds.common.log.annotation.Log;
import com.ms3ds.common.log.enums.BusinessType;
import com.ms3ds.common.security.annotation.RequiresPermissions;
import com.ms3ds.mineInfo.domain.Alarm;
import com.ms3ds.mineInfo.service.IAlarmService;
import com.ms3ds.common.core.web.controller.BaseController;
import com.ms3ds.common.core.web.domain.AjaxResult;
import com.ms3ds.common.core.utils.poi.ExcelUtil;
import com.ms3ds.common.core.web.page.TableDataInfo;

/**
 * 告警信息Controller
 * 
 * @author zlw
 * @date 2025-09-17
 */
@RestController
@RequestMapping("/alarm")
public class AlarmController extends BaseController
{
    @Autowired
    private IAlarmService alarmService;

    @Autowired
    private RemoteDeviceService remoteDeviceService;
    @Autowired
    private RemoteAreaService remoteAreaService;
    /**
     * 查询告警信息列表
     */
    @RequiresPermissions("mineInfo:alarm:list")
    @GetMapping("/list")
    public TableDataInfo list(Alarm alarm)
    {
        startPage();
        List<Alarm> list = alarmService.selectAlarmList(alarm);
        return getDataTable(list);
    }

    /**
     * 导出告警信息列表
     */
    @RequiresPermissions("mineInfo:alarm:export")
    @Log(title = "告警信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Alarm alarm)
    {
        List<Alarm> list = alarmService.selectAlarmList(alarm);
        ExcelUtil<Alarm> util = new ExcelUtil<Alarm>(Alarm.class);
        util.exportExcel(response, list, "告警信息数据");
    }

    /**
     * 获取告警信息详细信息
     */
    @RequiresPermissions("mineInfo:alarm:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(alarmService.selectAlarmById(id));
    }

    /**
     * 新增告警信息
     */
    @RequiresPermissions("mineInfo:alarm:add")
    @Log(title = "告警信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Alarm alarm)
    {
        return toAjax(alarmService.insertAlarm(alarm));
    }

    /**
     * 修改告警信息
     */
    @RequiresPermissions("mineInfo:alarm:edit")
    @Log(title = "告警信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Alarm alarm)
    {
        return toAjax(alarmService.updateAlarm(alarm));
    }

    /**
     * 删除告警信息
     */
    @RequiresPermissions("mineInfo:alarm:remove")
    @Log(title = "告警信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(alarmService.deleteAlarmByIds(ids));
    }

    /**
     * 根据矿山ID查询告警信息列表（已排序）
     */
    @RequiresPermissions("mineInfo:alarm:list")
    @GetMapping("/listByMineId")
    public AjaxResult listByMineId(@RequestParam("mineId") Long mineId)
    {
        List<Alarm> list = alarmService.selectAlarmListByMineId(mineId);
        return AjaxResult.success(list);
    }

    /**
     * 发布告警信息
     */
    @RequiresPermissions("mineInfo:alarm:add")
    @PostMapping("/warning/process")
    public ResponseEntity<?> processWarning(@RequestBody Map<String, Object> requestData) {
        // 检查dispatch字段是否为true
        Boolean dispatch = (Boolean) requestData.get("dispatch");
        if (dispatch != null && dispatch) {
            // 如果dispatch为true，不执行任何操作
            return ResponseEntity.ok().build();
        }

        // 创建Alarm对象并映射字段
        Alarm alarm = new Alarm();

        // 字段映射
        alarm.setMineId(parseLong(requestData.get("mineId")));
        alarm.setAlarmLevel(parseLong(requestData.get("warningLevel")));
        alarm.setAlarmInfo((String) requestData.get("warningInfo"));
        alarm.setTitle((String) requestData.get("warningTitle"));
        alarm.setAlarmType(parseLong(requestData.get("warningType")));

        // 设置默认值
        alarm.setCondition("0"); // 默认状态为0
        // alarmTime会在insertAlarm方法中自动设置为当前时间
        alarm.setUpdateTime(null); // updateTime默认为null

        // 调用服务层插入告警信息
        alarmService.insertAlarm(alarm);

        // 返回alarm的id给前端
        Map<String, Object> response = new HashMap<>();
        response.put("id", alarm.getId());
        return ResponseEntity.ok(response);

    }


    // 辅助方法：安全地将对象转换为Long
    private Long parseLong(Object value) {
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 更新告警状态为已处理（支持查询参数）
     */
    @RequiresPermissions("mineInfo:alarm:edit")
    @Log(title = "告警信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateCondition")
    public AjaxResult updateCondition(@RequestParam("warningId") Long warningId) {
        Alarm alarm = new Alarm();
        alarm.setId(warningId);
        alarm.setCondition("1");
        return toAjax(alarmService.updateAlarmCondition(alarm));
    }
    /**
     * 统计不同类型告警的数量
     */
    @RequiresPermissions("mineInfo:alarm:list")
    @GetMapping("/countAlarmTypes")
    public AjaxResult countAlarmTypes(Alarm alarm) {
        Map<String, Integer> countResult = alarmService.countAlarmTypes(alarm);
        Map<String, Object> result = new HashMap<>();
        result.put("chartData", countResult);
        return AjaxResult.success(result);
    }

    /**
     * 根据设备类型查询统计数据(sensor/camera)
     */
    @RequiresPermissions("mineInfo:alarm:list")
    @GetMapping("/statistics")
    public AjaxResult getStatisticsByType(@RequestParam("type") String type, 
                                          @RequestParam(value = "id", required = false) Long mineId) {
        // 获取设备总数
        int total = 0;
        int online = 0;
        
        // 如果提供了mineId，则按矿山统计设备数
        if (mineId != null) {
            // 获取该矿山的所有区域
            R<List<Area>> areaResult = remoteAreaService.getAreaListByMineIdForRemote(mineId);
            if (areaResult != null && areaResult.getData() != null && !areaResult.getData().isEmpty()) {
                List<Area> areas = areaResult.getData();
                List<Long> areaIds = areas.stream().map(Area::getId).collect(Collectors.toList());
                
                // 查询这些区域下的所有设备
                Device deviceQuery = new Device();
                // listForRemote自动查DelFlag为0的数据

                R<List<Device>> response = remoteDeviceService.listForRemote(deviceQuery);
                if (response != null && response.getData() != null) {
                    // 过滤出属于这些区域的设备
                    List<Device> devicesInAreas = response.getData().stream()
                            .filter(device -> device.getAreaId() != null && areaIds.contains(device.getAreaId()))
                            .collect(Collectors.toList());
                    total = devicesInAreas.size();
                }
            }
        } else {
            // 没有提供mineId，查询所有有效设备
            Device deviceQuery = new Device();
            deviceQuery.setDelFlag("1");
            
            R<List<Device>> response = remoteDeviceService.listForRemote(deviceQuery);
            List<Device> deviceList = response.getData();
            total = deviceList != null ? deviceList.size() : 0;
        }
        
        online = total; // 在线数等于总数

        // 创建Alarm查询条件
        List<Alarm> alarmList = new ArrayList<>();
        // 如果提供了mineId，添加矿山ID作为查询条件
        if (mineId != null) {
            alarmList = alarmService.selectAlarmListByMineId(mineId);
        } else {
            Alarm alarmQuery = new Alarm();
            alarmList = alarmService.selectAlarmList(alarmQuery);
        }

        // 根据type类型设置不同的查询条件
        List<Map<String, Object>> logList = new ArrayList<>();
        int warning = 0;

        if ("sensor".equals(type)) {
            // 过滤alarmType为1或2的告警并转换格式
            logList = alarmList.stream()
                    .filter(alarm -> alarm.getAlarmType() != null &&
                            (alarm.getAlarmType() == 1 || alarm.getAlarmType() == 2))
                    .map(this::convertAlarmToMap)
                    .collect(Collectors.toList());
            warning = logList.size();
        } else if ("camera".equals(type)) {
            // 过滤alarmType为4的告警并转换格式
            logList = alarmList.stream()
                    .filter(alarm -> alarm.getAlarmType() != null && alarm.getAlarmType() == 4)
                    .map(this::convertAlarmToMap)
                    .collect(Collectors.toList());
            warning = logList.size();
        }

        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("online", online);
        result.put("warning", warning);
        result.put("log", logList);

        return AjaxResult.success(result);
    }

    /**
     * 将Alarm对象转换为指定格式的Map
     */
    private Map<String, Object> convertAlarmToMap(Alarm alarm) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", alarm.getTitle());
        
        // level映射：1是一般告警，2是严重告警，3是紧急告警
        String levelDesc = "未知告警";
        if (alarm.getAlarmLevel() != null) {
            switch (alarm.getAlarmLevel().intValue()) {
                case 1:
                    levelDesc = "一般告警";
                    break;
                case 2:
                    levelDesc = "严重告警";
                    break;
                case 3:
                    levelDesc = "紧急告警";
                    break;
                default:
                    levelDesc = "未知告警";
                    break;
            }
        }
        map.put("level", levelDesc);
        
        // time只取日期部分
        if (alarm.getAlarmTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            map.put("time", sdf.format(alarm.getAlarmTime()));
        } else {
            map.put("time", "");
        }
        return map;
    }

}

